BUILD = DEBUG
BUILD = RELEASE

CFLAGS = -Wall -Wextra -std=gnu90
LDFLAGS = -lm

ifeq ($(BUILD), DEBUG)
	CFLAGS += -g -O0 -DDEBUG
endif

ifeq ($(BUILD), RELEASE)
	CFLAGS += -Werror -O2
endif

EXECUTABLES = music-play music-stop music-skip rng

all: $(EXECUTABLES)

music-play: config.h music-play.o config.o findhome.o blacklist.o choose.o filter.o filename.o random.o xtea.o encrypt.o
	$(CC) $(CFLAGS) -o music-play music-play.o random.o findhome.o encrypt.o xtea.o choose.o filter.o blacklist.o filename.o config.o $(LDFLAGS)

music-play.o: music-play.c
	$(CC) $(CFLAGS) -c -o music-play.o music-play.c

random.o: random.c random.h
	$(CC) $(CFLAGS) -c -o random.o random.c

findhome.o: findhome.c findhome.h
	$(CC) $(CFLAGS) -c -o findhome.o findhome.c

blacklist.o: blacklist.c blacklist.h
	$(CC) $(CFLAGS) -c -o blacklist.o blacklist.c

filename.o: filename.c filename.h
	$(CC) $(CFLAGS) -c -o filename.o filename.c

filter.o: filter.c filter.h
	$(CC) $(CFLAGS) -c -o filter.o filter.c

config.o: config.c config.h
	$(CC) $(CFLAGS) -c -o config.o config.c

choose.o: choose.c choose.h
	$(CC) $(CFLAGS) -c -o choose.o choose.c 

music-stop.o: music-stop.c
	$(CC) $(CFLAGS) -c -o music-stop.o music-stop.c

music-stop: config.h music-stop.o config.o findhome.o
	$(CC) $(CFLAGS) -o music-stop music-stop.o config.o findhome.o $(LDFLAGS)

music-skip.o: music-skip.c
	$(CC) $(CFLAGS) -c -o music-skip.o music-skip.c

music-skip: config.h music-skip.o config.o findhome.o
	$(CC) $(CFLAGS) -o music-skip music-skip.o config.o findhome.o $(LDFLAGS)

encrypt.o: encrypt.c encrypt.h
	$(CC) $(CFLAGS) -c -o encrypt.o encrypt.c

xtea.o: xtea.c xtea.h
	$(CC) $(CFLAGS) -c -o xtea.o xtea.c

rng.o: rng.c
	$(CC) $(CFLAGS) -c -o rng.o rng.c

rng: rng.o random.o encrypt.o xtea.o config.o findhome.o
	$(CC) $(CFLAGS) -o rng rng.o findhome.o random.o encrypt.o xtea.o config.o

check: 
	@echo Test the RNG. Requires dieharder. Produces a very large temporary file.
	./rng | dd if=/dev/stdin of=random_data bs=10000 count=100000 iflag=fullblock
	dieharder -a -f random_data -g 201 | tee rng-test-log
	rm random_data

clean:
	rm -f *.o $(EXECUTABLES)

ifeq ($(BUILD), RELEASE)
install: really-install
else
install: install-error
endif

install-error:
	@echo "***Build is DEBUG. Don't install at all."

really-install: music-play music-stop music-skip dmusic 
	install -m 755 -t /usr/local/bin music-play
	install -m 755 -t /usr/local/bin music-stop
	install -m 755 -t /usr/local/bin music-skip
	install -m 755 -t /usr/local/bin dmusic

configure: music-menu
	install -m 644 -T music-menu $(HOME)/.music-menu

uninstall:
	rm /usr/local/bin/music-play
	rm /usr/local/bin/music-stop
	rm /usr/local/bin/music-skip
	rm /usr/local/bin/dmusic

